package griffin.website;

import griffin.logic.UserLogic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.pm.ActivityInfo;

public class ContentList extends Activity {
	private static final String SOAP_ACTION_ADDBOOKMARK = "http://tempuri.org/addBookmark";
	private static final String METHOD_NAME_ADDBOOKMARK = "addBookmark";
	private static final String SOAP_ACTION_GETCATEEVALUATION = "http://tempuri.org/getCateEvaluation";
	private static final String METHOD_NAME_GETCATEEVALUATION = "getCateEvaluation";
	private static final String NAMESPACE = "http://tempuri.org/";
	// private static final String URL =
	// "http://griffin.ciandt.cn/Sservice1.asmx";
	private static final String URL = "http://192.168.3.130:8080/Sservice1.asmx";

	private static final String SOAP_ACTION_GETEVALUATION = "http://tempuri.org/getSiteEvaluation";
	private static final String METHOD_NAME_GETEVALUATION = "getSiteEvaluation";
	private static final String SOAP_ACTION_SETEVALUATION = "http://tempuri.org/setEvaluation";
	private static final String METHOD_NAME_SETEVALUATION = "setEvaluation";

	private int loginUserID = 0;
	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	private static final String TAG = "[contentlist]";
	String[] stringEvaluationitems;
	int[] intEvaluationitems = { 1, 2, 3 };

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "[onCreate...] ");
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.contentlist);

		getLoginInfo();
		showCategoryTitle();
		getContent();
	}

	private void getContent() {
		prepareGetContent();

		ListView listView = (ListView) findViewById(R.id.lsvContentList);
		listView.setAdapter(new EvaluationAdapter());
		listView.setOnItemClickListener(new ItemClickListener());
		// String curcateid = getCurCategoryID();
		// SimpleAdapter adapter = new
		// SimpleAdapter(this,getContentData(curcateid),R.layout.contentitem,
		// new String[]{"sitename","rbLevel"},
		// new int[]{R.id.siteName,R.id.rbLevel});
	}

	class EvaluationAdapter extends ArrayAdapter<String> {
		public EvaluationAdapter() {
			super(ContentList.this, R.layout.contentitem, stringEvaluationitems);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (position + 1 > list.size())
				return null;

			Map<String, Object> map = list.get(position);
			LayoutInflater inflater = getLayoutInflater();
			View row = inflater.inflate(R.layout.contentitem, parent, false);
			TextView textView = (TextView) row.findViewById(R.id.siteName);
			textView.setText(map.get("sitename").toString());
			RatingBar ratingBar = (RatingBar) row.findViewById(R.id.rbLevel);
			ratingBar
					.setRating(Float.parseFloat(map.get("rbLevel").toString()));

			Log.d(TAG,
					"[EvaluationAdapter.sitename( "
							+ map.get("sitename").toString() + ").siteid("
							+ map.get("siteid").toString() + " ).setRating("
							+ Float.parseFloat(map.get("rbLevel").toString())
							+ ")]");
			return row;
		}

	}

	private void showCategoryTitle() {
		Button btnTitle = (Button) findViewById(R.id.btnContentCategoryTitle);
		btnTitle.getBackground().setAlpha(230);
		btnTitle.setText(getCurCategoryName());
		// btnTitle.setText(getCurCategoryName()+getCurCategoryID());
		btnTitle.setOnClickListener(new ButtonTitleClickListener());
	}

	class ItemClickListener implements OnItemClickListener {
		public void onItemClick(AdapterView<?> arg0,// The AdapterView where the
													// click happened
				View arg1,// The view within the AdapterView that was clicked
				int arg2,// The position of the view in the adapter
				long arg3// The row id of the item that was clicked
		) {
			LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
			View view = inflater.inflate(R.layout.contentpopup, null);	
			final HashMap<String, Object> item = (HashMap<String, Object>) list
					.get(arg2);
			displayToast((String) item.get("sitename"));

			createPopup(view);
			addVisitEvent(view, item);
			addBookmarkAddEvent(view, item);			
			addEvaluationEvent(view, item);

		} // onItemClick

		private void createPopup(View view) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					ContentList.this);
			builder.setView(view);
			builder.setCancelable(false).setNegativeButton("Exit operation",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
							getContent();

						}
					});
			builder.create();
			builder.show();
		}
		
		private void addVisitEvent(View view, final HashMap<String, Object> item) {
			Button btnVisit = (Button) view.findViewById(R.id.btnVisit);
			btnVisit.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					openUrl((String) item.get("siteurl"));
				}
			});
		}
		
		private void addBookmarkAddEvent(View view,
				final HashMap<String, Object> item) {
			ImageButton imgbtnAddBookmark = (ImageButton) view
					.findViewById(R.id.imgbtnAddBookmark);
			imgbtnAddBookmark.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {

					if (loginUserID != 0) {
						if (addBookmark((String) item.get("sitename"),
								(String) item.get("siteurl"))) {
							displayToast("Add bookmark Success!");
						} else {
							displayToast("The bookmark already had added.");
						}
					} else {
						askLoginTip();
					}

				}
			});
		}

		private void addEvaluationEvent(View view,
				final HashMap<String, Object> item) {
			RatingBar rtbEvaluation = getSiteEvaluation(view, item);
			final int siteID = Integer.parseInt(item.get("siteid").toString());
			final int cateID = Integer.parseInt(getCurCategoryID());
			rtbEvaluation
					.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {

						public void onRatingChanged(RatingBar ratingBar,
								float rating, boolean fromUser) {

							try {
								SoapObject request = new SoapObject(NAMESPACE,
										METHOD_NAME_SETEVALUATION);
								request.addProperty("userID", loginUserID);
								request.addProperty("siteID", siteID);
								request.addProperty("cateid", cateID);
								request.addProperty("evaluationNumber",
										String.valueOf(rating));

								if (loginUserID == 0) {
									askLoginTip();
								} else {
									SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
											SoapEnvelope.VER11);
									envelope.dotNet = true;
									envelope.setOutputSoapObject(request);

									HttpTransportSE androidHttpTransport = new HttpTransportSE(
											URL);
									androidHttpTransport
											.call(SOAP_ACTION_SETEVALUATION,
													envelope);

								}// end if-else
							} catch (Exception ex) {
								ex.printStackTrace();
							}

							ratingBar.setRating(rating);
							Toast.makeText(ContentList.this,
									"rating:" + String.valueOf(rating),
									Toast.LENGTH_LONG).show();

						}
					});
		}

		private RatingBar getSiteEvaluation(View view,
				final HashMap<String, Object> item) {
			RatingBar rtbEvaluation = (RatingBar) view
					.findViewById(R.id.rtbEvaluation);
			try {
				SoapObject request = new SoapObject(NAMESPACE,
						METHOD_NAME_GETEVALUATION);
				request.addProperty("userID", loginUserID);
				request.addProperty("siteID",
						Integer.parseInt(item.get("siteid").toString()));

				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
						SoapEnvelope.VER11);
				envelope.dotNet = true;
				envelope.setOutputSoapObject(request);

				HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
				androidHttpTransport.call(SOAP_ACTION_GETEVALUATION, envelope);

				Object result = (Object) envelope.getResponse();
				float rating = Float.parseFloat(result.toString());
				rtbEvaluation.setRating(rating);

			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return rtbEvaluation;
		}

		private void askLoginTip() {
			// Toast.makeText(contentlist.this, "You are not sign in..",
			// Toast.LENGTH_SHORT).show();
			AlertDialog.Builder builder = new AlertDialog.Builder(
					ContentList.this);
			builder.setTitle("You are not sign in.Login now?")
					.setPositiveButton("Yes!",
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface arg0,
										int arg1) {
									openIntenInView("Login", ContentList.this);
								}
							});
			builder.setCancelable(false).setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			builder.create();
			builder.show();
		}
	}

	public void openIntenInView(String name, Context context) {
		Intent intent = new Intent();
		intent.putExtra("winname", name);
		intent.setClass(context, TabBarFramework.class);
		startActivity(intent);
	}

	class ButtonTitleClickListener implements OnClickListener {
		public void onClick(View v) {

			SharedPreferences loginInfo = getSharedPreferences(
					"griffin.website.curcate", 0);
			SharedPreferences.Editor editor = loginInfo.edit();
			String strCurCategoryID = getCurCategoryID().substring(0,
					getCurCategoryID().length() - 2);
			if (loginInfo.contains("curcategoryid"))
				editor.remove("curcategoryid");
			if (loginInfo.contains("curcategoryname"))
				editor.remove("curcategoryname");
			editor.putString("curcategoryid", strCurCategoryID);
			editor.putString("curcategoryname",
					getCurCategoryNameNew(strCurCategoryID));
			editor.commit();

			ContentList.this.finish();
		}
	}

	private String getCurCategoryNameNew(String curCategoryID) {
		String resultStr = "";
		String databaseFilename = TabBarFramework.DATABASE_PATH + "/"
				+ TabBarFramework.DATABASE_FILENAME;
		SQLiteDatabase db;
		db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);

		Cursor result = null;
		if (curCategoryID.length() == 1) {
			result = db.rawQuery(
					"SELECT VG_NAME  FROM VG_TopCategories where VG_ID="
							+ curCategoryID, null);
		} else {
			result = db.rawQuery(
					"SELECT VG_ENGLISH  FROM VG_WebCategories where VG_ID="
							+ curCategoryID, null);
		}

		if (result.moveToFirst()) {
			while (!result.isAfterLast()) {

				resultStr = result.getString(0);
				result.moveToNext();
			}
		}
		result.close();
		db.close();

		return resultStr;
	}

	private boolean addBookmark(String bookmarkName, String bookmarkUrl) {
		boolean isSuccess = false;

		if (isLogined()) {
			try {
				SoapObject request = new SoapObject(NAMESPACE,
						METHOD_NAME_ADDBOOKMARK);

				request.addProperty("userid", loginUserID);
				request.addProperty("bookmarkName", bookmarkName);
				request.addProperty("bookmarkUrl", bookmarkUrl);

				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
						SoapEnvelope.VER11);
				envelope.dotNet = true;
				envelope.setOutputSoapObject(request);

				HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
				androidHttpTransport.call(SOAP_ACTION_ADDBOOKMARK, envelope);

				Object result = (Object) envelope.getResponse();
				if (Integer.parseInt(result.toString()) == 1) {
					isSuccess = true;
					setNotifyBookmarkUpdatedFlag();
				}

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		return isSuccess;
	}

	private boolean isLogined() {
		if (loginUserID == 0) {
			return false;
		} else {
			return true;
		}
	}

	private void setNotifyBookmarkUpdatedFlag() {
		SharedPreferences bookmarkupdateInfo = getSharedPreferences(
				"griffin.website.bookmarkupdatedflag", 0);
		SharedPreferences.Editor editor = bookmarkupdateInfo.edit();
		if (bookmarkupdateInfo.contains("bookmarkupdatedflagathome"))
			editor.remove("bookmarkupdatedflagathome");
		if (bookmarkupdateInfo.contains("bookmarkupdatedflagatbookmark"))
			editor.remove("bookmarkupdatedflagatbookmark");
		// notify home activity to update bookmark list
		editor.putBoolean("bookmarkupdatedflagathome", true);
		// notify bookmark activity to update bookmark list
		editor.putBoolean("bookmarkupdatedflagatbookmark", true);
		editor.commit();
	}

	private void getLoginInfo() {
		AtomicReference<String> strUsername = new AtomicReference<String>("");
		AtomicReference<String> strPassword = new AtomicReference<String>("");
		AtomicInteger userid = new AtomicInteger(0);

		UserLogic userLogic = new UserLogic(this);
		if (userLogic.getLoginUser(strUsername, strPassword, userid)) {
			loginUserID = userid.get();
		}
	}

	private void openUrl(String url) {
		Uri uri = Uri.parse(url);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent);
	}

	public void displayToast(String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}

	private String getCurCategoryID() {
		SharedPreferences curcateInfo = getSharedPreferences(
				"griffin.website.curcate", 0);
		return curcateInfo.getString("curcategoryid", "");
	}

	private String getCurCategoryName() {
		SharedPreferences curcateInfo = getSharedPreferences(
				"griffin.website.curcate", 0);
		return curcateInfo.getString("curcategoryname", "");
	}

	private void prepareGetContent() {
		list.clear();
		String cateid = getCurCategoryID();
		// get rbLevel
		Map<String, Object> evalEvaluations = getrbLevels(cateid);
		Log.d(TAG,
				"[getrbLevels( " + cateid + " ).size(" + evalEvaluations.size()
						+ ")]");

		String databaseFilename = TabBarFramework.DATABASE_PATH + "/"
				+ TabBarFramework.DATABASE_FILENAME;
		SQLiteDatabase db;

		db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
		Cursor result = db.rawQuery(
				"SELECT VG_ID, VG_ENGLISH, VG_HTTPURL FROM VG_WebSites where VG_PARENT = "
						+ cateid, null);
		if (result.moveToFirst()) {
			while (!result.isAfterLast()) {
				String siteid = result.getString(0);
				String sitename = result.getString(1);
				String siteurl = result.getString(2);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("sitename", sitename);
				map.put("siteurl", siteurl);
				map.put("siteid", siteid);
				if (evalEvaluations.containsKey(siteid)) {
					map.put("rbLevel", evalEvaluations.get(siteid));
				} else {
					map.put("rbLevel", "0");
				}
				list.add(map);
				result.moveToNext();
			}
		}
		result.close();
		db.close();
		stringEvaluationitems = new String[list.size()];

		Log.d(TAG, "[lists( " + cateid + " ).size(" + list.size() + ")]");
	}

	private Map<String, Object> getrbLevels(String curcateid) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			SoapObject request = new SoapObject(NAMESPACE,
					METHOD_NAME_GETCATEEVALUATION);
			request.addProperty("cateID", curcateid);
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.dotNet = true;
			envelope.setOutputSoapObject(request);

			HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
			androidHttpTransport.call(SOAP_ACTION_GETCATEEVALUATION, envelope);

			Object result = (Object) envelope.getResponse();
			JSONObject jsonObj = new JSONObject(result.toString());
			JSONArray evaluationkArr = jsonObj.getJSONArray("evaluation");

			for (int i = 0; i < evaluationkArr.length(); i++) {
				map.put(evaluationkArr.getJSONObject(i).getString("siteid"),
						evaluationkArr.getJSONObject(i).getString(
								"evaluationnumber"));
			}
		} catch (Exception ex) {
//			String errmsg = ex.toString();
//			errmsg += "asd";
		}

		return map;
	}

	@Override
	public boolean onTouchEvent(MotionEvent evt) {
		if (evt.getAction() == MotionEvent.ACTION_DOWN) {
			displayToast("on touch event");
		}
		return true;
	}
}
